
//
// 110222 - AH - Created.
//

package org.soekrat.gui.swing.studio;

import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import org.soekrat.engine.Soekrat2Engine;

/**
 * <p>
 *   Pane with 
 *   {@link RatStudioView}s that can be teared of.
 * </p>
 * @author Arne Halvorsen (AH) 
 * @author Laetitia Le Chatton (LLC) 
 */
@SuppressWarnings("serial")
public final class RatStudioViewPane extends JPanel 
{
  private final Map<String, RatStudioView> m_views=
    new HashMap<String, RatStudioView>();
  
  private final List<RatStudioView> m_active=new ArrayList<RatStudioView>();
  
  private final JTabbedPane m_tp=new JTabbedPane();
  
  private final Soekrat2Engine m_engine;
  
  /**
   * <p>
   *   Constructor,
   * </p>
   */
  public RatStudioViewPane(Soekrat2Engine engine)
  {
    if (engine==null)
    {
      throw new NullPointerException("engine");
    }
    
    m_engine=engine;
  
    setLayout(new BorderLayout());
    
    add(m_tp, BorderLayout.CENTER);
  }
  
  public Soekrat2Engine getEngine(){ return m_engine; }
  
  void tearOff(RatStudioView v)
  {
    if (v==null)
    {
      throw new NullPointerException("v");
    }
    
    m_tp.remove(v);
    m_active.remove(v);
    
    RatStudioViewDialog dlg=new RatStudioViewDialog();
    dlg.showDialog(v);
  }
  
  void putBack(RatStudioView v)
  {
    if (v==null)
    {
      throw new NullPointerException("v");
    }
    
    int idx=Math.abs(Collections.binarySearch(m_active, v))-1;
    m_active.add(idx, v);
    
    m_tp.removeAll();
    for (RatStudioView curr : m_active)
    {
      m_tp.addTab(curr.getTitle(), curr);
    }
  }
  
  /**
   * <p>
   *   Adds view.
   * </p>
   * @param view View to add.
   * @throws IllegalArgumentException If view with title already added.
   */
  public void add(RatStudioView view)
  {
    if (view==null)
    {
      throw new NullPointerException("view");
    }
    
    String title=view.getTitle();
    
    if (m_views.containsKey(title))
    {
      throw new IllegalArgumentException("duplicate : "+title);
    }
    
    int idx=m_views.size();
    
    m_views.put(title, view);
    m_active.add(view);
    m_tp.addTab(title, view);
    
    view.setContext(this, idx);
  }
  
}
